<template>
  <div class="app-container">
    <div class="search-container" v-if="isSearch || showAdd === 1">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="success" @click="handleAdd()" v-if="showAdd === 1"
            ><i-ep-plus />新增</el-button
          >
        </el-form-item>
        <el-form-item
          v-for="(item, index) in searchList"
          :key="index"
          :label="item.description"
          v-if="isSearch"
        >
          <el-input
            v-model="queryParams[item.columnName]" placeholder="请输入"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery" v-if="isSearch"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="handleResetQuery" v-if="isSearch"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="tableDataRef"
        :data="tableDataList"
        style="width: 100%"
      >
        <el-table-column
            v-for="(item, index) in tableColumnList"
            :key="index"
            :label="item.description"
            :prop="item.columnName"
            :show-overflow-tooltip="true"
            :min-width="item.width"
        >
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220" v-if="showEdit === 1 || showDelete === 1">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleEdit(scope.row.id)"
              v-if="showEdit === 1"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
              v-if="showDelete === 1"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.size"
        @pagination="handleQuery"
      />
    </el-card>
    <!-- 新增弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增"
      min-width="500px"
      @close="handleCloseDialog"
    >
      <v-form-render :form-json="formJson" :form-data="addFormData" :option-data="optionData" ref="vFormRef">
      </v-form-render>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  defineOptions({
    name: "Diytable",
    inheritAttrs: false,
  });

  import router from "@/router";
  import DiytableAPI from "@/api/diytable";
  import { changeTableData, transferFormData } from "@/utils/index";
  import DesformAPI from "@/api/desform";

  const route = useRoute();

  const queryFormRef = ref(ElForm);

  const loading = ref(false);
  const total = ref(0);

  const queryParams = reactive({
    page: 1,
    size: 10,
    id: route.params.id,
    dataSource: null,
  });
  const tableColumnList = ref([]);
  const tableDataRef = ref(null);
  const tableDataList = ref([]);
  const widgetList = ref([]); // 原始表单组件
  /** 查询 */
  function handleQuery() {
    loading.value = true;
    DiytableAPI.GetTableData(queryParams)
      .then(({data}) => {
        tableDataList.value = data.list;
        total.value = data.total;

        // select、radio等数据加工
        DesformAPI.getByTableName(queryParams.dataSource)
        .then(({data}) => {
          if (data && data.jsonData){
            let json = JSON.parse(data.jsonData);
            widgetList.value = json.widgetList;
            changeTableData(tableDataList.value, widgetList.value);

            // 初始化新增弹出框表单
            formJson.widgetList = json.widgetList;
            formJson.formConfig = json.formConfig;
          }
        })
      })
      .finally(() => {
        loading.value = false;
      });
  }
  /** 重置查询 */
  function handleResetQuery() {
    queryFormRef.value.resetFields();
    queryParams.page = 1;
    for (let key in queryParams){
      if (key != "page" && key != "size" && key != "id" && key != "dataSource"){
        queryParams[key] = '';
      }
    }
    handleQuery();
  }

  const searchList = ref([]);
  const isSearch = ref(false);
  watch(() => tableColumnList.value, (newItems, oldItems) => {
    searchList.value = [];
    newItems.forEach((item, index) => {
      if (item.searchType && item.searchType != 0) {
        searchList.value.push(item);
        queryParams[item.columnName] = '';
        isSearch.value = true;
      }
    });
  }, {
    deep: true, // 开启深度监听
  });

  // 按钮集
  const showAdd = ref(0);
  const showEdit = ref(0);
  const showDelete = ref(0);

  // 新增修改删除
  const dialogVisible = ref(false);
  const formJson = reactive({"widgetList":[],"formConfig":{"modelName":"formData","refName":"vForm","rulesName":"rules","labelWidth":80,"labelPosition":"left","size":"","labelAlign":"label-left-align","cssCode":"","customClass":"","functions":"","layoutType":"PC","jsonVersion":3,"onFormCreated":"","onFormMounted":"","onFormDataChange":""}})
  const addFormData = reactive({})
  const optionData = reactive({})
  const vFormRef = ref(null)
  const formDataId = ref(null);

  function handleAdd(){
    if (queryParams.dataSource){
      dialogVisible.value = true;
      formDataId.value = null;
    }
    else{
      ElMessage.warning("请选择数据源");
    }
  }

  function handleEdit(id){
    dialogVisible.value = true;
    formDataId.value = id;
    DesformAPI.GetFormDataById(queryParams.dataSource, id)
      .then(({data}) => {
        transferFormData(data, widgetList.value)
        for(let key in data){
          vFormRef.value.setFieldValue(key, data[key]);
        }
      })
  }

  function handleDelete(id){
    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
      () => {
        loading.value = true;
        DesformAPI.deleteFormData(queryParams.dataSource, id)
          .then(() => {
            ElMessage.success("删除成功");
            handleQuery();
          })
          .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消删除");
      }
    );
  }

  function handleCloseDialog(){
    dialogVisible.value = false;
    vFormRef.value.resetForm();
  }

  function handleSubmit(){
    vFormRef.value.getFormData().then(thisFormData => {
      thisFormData.tableName = queryParams.dataSource;
      loading.value = true;
      if (formDataId.value){
        thisFormData.id = formDataId.value;
        DesformAPI.updateFormData(thisFormData)
          .then(({data}) => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
      else{
        DesformAPI.insertFormData(thisFormData)
          .then(({data}) => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }).catch(error => {
      // Form Validation failed
      ElMessage.error(error)
    })
  }

  onMounted(() => {
    DiytableAPI.getTableColumns(route.params.id).then(({data}) => {
      if (data){
        tableColumnList.value = data;
        DiytableAPI.getById(route.params.id).then(({data}) => {
          if (data){
            queryParams.dataSource = data.dataSource;
            showAdd.value = data.showAdd;
            showEdit.value = data.showEdit;
            showDelete.value = data.showDelete;
            handleQuery();
          }
        })
      }
    })
  });
</script>
